const axios = require('axios');
const logger = require('../utils/logger');
// 引入依赖（假设使用CommonJS）
//const { CallbackService } = require('./services/CallbackService');
class CallbackService {
  static async notifyPushResult(pushResult) {
    try {
      if (!pushResult.callbackUrl) return;
      
      const payload = {
        event: 'push_completed',
        timestamp: new Date().toISOString(),
        data: {
          pushId: pushResult.pushId,
          successCount: pushResult.successCount,
          failCount: pushResult.failCount,
          details: pushResult.details
        }
      };

      await axios.post(pushResult.callbackUrl, payload, {
        timeout: 5000
      });

      logger.info('回调通知成功', {
        callbackUrl: pushResult.callbackUrl,
        pushId: pushResult.pushId
      });
    } catch (err) {
      logger.error('回调通知失败', {
        error: err.message,
        callbackUrl: pushResult.callbackUrl
      });
    }
  }

  static async notifyFailedPush(pushRecord) {
    try {
      if (!pushRecord.callbackUrl) return;
      
      const payload = {
        event: 'push_failed',
        timestamp: new Date().toISOString(),
        data: {
          pushId: pushRecord.id,
          userId: pushRecord.userId,
          error: pushRecord.errorMsg
        }
      };

      await axios.post(pushRecord.callbackUrl, payload, {
        timeout: 5000
      });
    } catch (err) {
      logger.error('失败推送回调通知失败', {
        error: err.message,
        callbackUrl: pushRecord.callbackUrl
      });
    }
  }
}

// 事件类型定义（增强可读性）
const EVENT_TYPES = {
  PUSH_COMPLETED: {
    name: 'push_completed',
    description: '消息推送成功事件'
  },
  PUSH_FAILED: {
    name: 'push_failed',
    description: '消息推送失败事件'
  },
  SUBSCRIPTION_UPDATED: {
    name: 'subscription_updated',
    description: '用户订阅状态更新事件'
  }
};


// 导出配置
module.exports = {
  retryPolicy: {
    maxAttempts: 3,
    delay: (attempt) => 1000 * Math.pow(2, attempt - 1), // 指数退避
    timeout: 5000,
    retryCondition: (error) => error.code === 'NETWORK_TIMEOUT' // 可选条件
  },
  eventTypes: Object.keys(EVENT_TYPES).reduce((acc, key) => {
    acc[key] = EVENT_TYPES[key].name;
    return acc;
  }, {}),
  CallbackService // 显式导出服务类
};

// module.exports = CallbackService;